package com.jhc.drone.communication.hook;


import com.jhc.drone.communication.network.Gateway;
import com.jhc.drone.communication.network.TcpGateway;
import com.jhc.drone.communication.network.UdpGateway;
import com.jhc.drone.communication.processor.PackUnpackMessageProcessorFactory;
import com.jhc.drone.communication.properties.ProtocolProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author lcp
 * @date 2025年01月2025/1/20 15:00
 * @describe
 */
@Component
@RequiredArgsConstructor
public class GatewayHook implements InitializingBean, DisposableBean {

    private final ProtocolProperties protocolProperties;

    private Gateway gateway;

    public void afterPropertiesSet() {
        switch (protocolProperties.protocol) {
            case UDP:
                try {
                    gateway = new UdpGateway(new PackUnpackMessageProcessorFactory());
                    gateway.init();
                    gateway.bind();
                } catch (Exception e) {
                    gateway.shutdown();
                }

                break;
            case TCP:
                try {
                    gateway = new TcpGateway(new PackUnpackMessageProcessorFactory());
                    gateway.init();
                    gateway.bind();
                } catch (Exception e) {
                    gateway.shutdown();
                }
                break;
            case MQTT:
                break;
            default:
                break;
        }
    }

    @Override
    public void destroy() throws Exception {
        if (Objects.nonNull(gateway)) {
            gateway.shutdown();
        }
    }
}
